using UnityEngine;

/// <summary>
/// 继承了MonoBehaviour的单例模式基类
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
    private static UnityEngine.Object obj = new UnityEngine.Object();
    private static T t;

    /// <summary>
    /// 引用
    /// </summary>
    /// <returns></returns>
    public static T Instance
    {
        get
        {
            if (t == null)
            {
                lock (obj)
                {
                    if (t == null)
                    {
                        GameObject monoObj = GameObject.Find("SingletonMono");
                        if (monoObj == null)
                        {
                            monoObj = new GameObject("SingletonMono");
                            DontDestroyOnLoad(monoObj);
                        }

                        t = monoObj.AddComponent<T>();
                    }
                }
            }
            return t;
        }
    }

    // 保护类型，虚函数
    public virtual void Awake()
    {
        if (t == null)
            t = this as T;
        //if (t == null)
        //    t = gameObject.GetComponent<T>();
    }
}